//
//  GpsManager.m
//  duzhoumo
//
//  Created by dzmmac on 15/8/31.
//  Copyright (c) 2015年 dzmmac. All rights reserved.
//

#import "GpsManager.h"
#import "UIDevice+IdentifierAddition.h"
#import "NSUserDefaults+Addition.h"
#import "CommoneTools.h"
#import "SVProgressHUD.h"
@implementation GpsManager

+(GpsManager *)shareManager{
    static GpsManager *instance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        instance = [[self alloc] init];
    });
    return instance;
}


-(void)startGPS{
    // 根据当前的地理位置的经纬度
    self.locationManager = [[CLLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    [self.locationManager startUpdatingLocation];
}

/**
 *  地理位置代理
 *
 *  @param manager   位置管理类
 *  @param locations 经纬度
 */
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    CLLocation *latestLocation = [locations firstObject];
    //根据经纬度解析成位置
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:latestLocation completionHandler:^(NSArray *placemark,NSError *error){
        if (error == nil) {
            CLPlacemark *mark = [placemark objectAtIndex:0];
            
            NSString *currentCity = [mark.locality stringByReplacingOccurrencesOfString:@"市" withString:@""];
            
            [[NSUserDefaults standardUserDefaults] setGPSCity:currentCity];
            
            
            // 获取上次用户选择的城市
            NSString *cacheCity = [[NSUserDefaults standardUserDefaults] getUserSelectedCity];
            
            // 如果未空 则默认选择当前城市
            if (cacheCity == nil) {
                
                [[NSUserDefaults standardUserDefaults] setUserSelectedCity:currentCity];
                [[NSNotificationCenter defaultCenter ] postNotificationName:GPSSuccess object:nil];
                
                NSString *cityId = [GpsManager isContaintCity:currentCity];
                if (cityId) {
                    [[NSUserDefaults standardUserDefaults] setUserSelectedCityID:cityId];
                }else{
                    [SVProgressHUD showErrorWithStatus:TipMessage duration:1];
                }
                
            }
            // 如果用户上次选择的城市和当前城市不同进行提示
            else if (![cacheCity isEqualToString:currentCity]) {
               
                self.mark = mark;

               self.cityId = [GpsManager isContaintCity:currentCity];
          
//                if (cityId) {
                    UIAlertView *alert = [[UIAlertView alloc ] initWithTitle:@"" message:[NSString stringWithFormat:@"定位您现在的位置是%@，是否切换？",mark.locality] delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
                    [alert show];
                    
//                }else{
//                    [HudManager showFailure:@"当城市未开通,请选择其他城市"];
//                }
            }
            // 当前城市和用户上次选择的城市相同
            else{
                
              //  [[NSNotificationCenter defaultCenter ] postNotificationName:GPSSuccess object:nil];
            }
         
        }
        // 定位失败
        else{
            
        }
    }];
    
    [self.locationManager stopUpdatingLocation];
    [self.locationManager setDelegate:nil];
  
}

/**
 *  GPS定位失败
 *
 *  @param manager 位置管理类
 *  @param error   错误信息
 */
- (void)locationManager: (CLLocationManager *)manager
       didFailWithError: (NSError *)error {
    [manager stopUpdatingLocation];
  
    
    if ( [error code] == kCLErrorDenied){
        [[[UIAlertView alloc ] initWithTitle:@"" message:@"定位失败，请开启定位:设置 > 隐私 > 位置 > 定位服务" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
    }
    [[NSNotificationCenter defaultCenter ] postNotificationName:GPSFailure object:nil];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    // 城市发生了改变
    if (buttonIndex == 1) {
        
        
        if (self.cityId == nil) {
            [SVProgressHUD showErrorWithStatus:TipMessage duration:1];
        }
        [[NSUserDefaults standardUserDefaults] setUserSelectedCityID:self.cityId];
        [[NSUserDefaults standardUserDefaults] setUserSelectedCity:self.mark.locality];
        [[NSNotificationCenter defaultCenter ] postNotificationName:GPSSuccess object:nil];
   
    }
}

// 是否包含已开通城市,如果包含返回城市ID
+(NSString *)isContaintCity:(NSString *)cgsCity{
    
    NSDictionary *cityDic = [CommoneTools loadDishFile:@"CityArea"];
    NSArray *areaList = [cityDic objectForKey:@"CityAreaList"];
    
    for (NSDictionary *cityModel in areaList) {
        NSString *cityName = [cityModel objectForKey:@"CityName"];
        if ([cgsCity isEqualToString:cityName]) {
            return [cityModel objectForKey:@"CityId"];
        }
    }
    return nil;
}

@end
